package tj.warning.pull.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import tj.warning.pull.mapper.report2.Report2Mapper;
import tj.warning.pull.mapper.report3.Report3Mapper;
import tj.warning.pull.model.Repository;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ThreadService {

    @Autowired
    @Qualifier("sqlSessionFactoryReport2")
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    @Qualifier("sqlSessionTemplateReport3")
    private SqlSessionTemplate sqlSessionTemplate;

    @Resource
    private Report3Mapper report3Mapper;
    @Resource
    private Report2Mapper report2Mapper;

    @Async("searchTaskExecutor")
    public void collectAndSaveRemoteData(Report3Mapper report3Mapper, List<String> tableNames, String endTime){

        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            Cursor<Map<String,String>> res = sqlSession.getMapper(Report2Mapper.class).getWellDrillingDetails(tableNames,endTime);
            List<Map<String,String>> temp=new LinkedList<>();
            res.forEach(it->{
                if(temp.size()<150){
                    temp.add(it);
                }else{
                    temp.add(it);
                    dataGroupAndSave(temp,report3Mapper);
                    temp.clear();
                }
            });
            dataGroupAndSave(temp,report3Mapper);
        }catch (Exception exception){
            log.error(exception.getMessage());
            //throw exception;
        }

    }

    /**
     * 数据分组并保存
     * @param list
     * @param report3Mapper
     */
    public void dataGroupAndSave(List<Map<String,String>> list, Report3Mapper report3Mapper){
        Map<String,List<Map<String,String>>> result=list.stream()
                .collect(Collectors.groupingBy(map->map.get("JH")));

        result.keySet().forEach(item->{
            String tableName="LTD_"+item.replace('-', '_').toUpperCase().trim();
            tableName = "\""+tableName+"\"";
            report3Mapper.insertBatchByTableName(tableName,result.get(item));

            log.info("tableName:{},data:{}",tableName,result.get(item).stream().map(i->i.get("JH")).collect(Collectors.toList()));
        });

    }


    public void dataSave(List<Map<String,String>> list,String tableName){

        //System.out.println("list.size = " + list.size());
        if(list==null||list.size()==0||tableName==null||tableName.equals("\"\"")){
            //log.warn("list.size:{},tableName:{}",list.size(),tableName);
            return;
        }
        try {
            report3Mapper.insertBatchByTableName(tableName, list);
        }catch (Exception ex){
            log.error(list.toString());
            log.error(ex.getMessage());
            throw ex;
        }
    }
    @Async("insertTaskExecutor")
    public void syncData(List<String> tableList){
        report3Mapper.syncData(tableList,"'"+Repository.collectEndTime+"'");
    }


}
